<?php
namespace app\view\controller;

use app\api\controller\BaseController;
use app\common\exception\SuccessException;
use app\facade\view\GoodsService;
use think\facade\Request;
use think\Db;

/**
 * 首页
 */
class Goods extends BaseController
{

    /** 创建 */
    public function create()
    {
        // $data = $bookValidate->scene('save')->goCheck();
        $params = Request::param();
        $res = GoodsService::createRow($params);
        throw new SuccessException([ 'error_code' => $res['error'], 'content' => $res['content'] ,'msg' => $res['message'] ]);
    }

    /** 修改 */
    public function update()
    {
        // $data = $bookValidate->scene('save')->goCheck();
        $params = Request::param();
        $res = GoodsService::updateRow($params);
        throw new SuccessException(['msg' => '更新成功']);
    }

    /**
     * 列表
     */
    public function list()
    {
        $params = Request::param();
        $pageSize = $params['pageSize'] ?? 10;
        $pageNumber = $params['pageNumber'] ?? 1;
        $where = [
            'category_id' => $params['id'],
        ];
        $res = Db::table('times_goods')
        ->where($where)
        ->field('*')
        ->order('create_date', 'desc')
        ->paginate($pageSize, false, ["page" => $pageNumber])
        ->toArray();
        throw new SuccessException([ 'content' => $res ,'msg' => 'SUCCESS' ]);
    }

    /**
     * 详情
     */
    public function detailed()
    {
        $params = Request::param();
        $where = [
            'goods_id' => $params['id']
        ];
        $field = 'goods_id, category_id, grade_id, item_id, volume, custom, interval_time, text';
        $res = GoodsService::getRow($where, $field)->toArray();
        // 获取文字
        if($res['item_id']) {
            $item_id = explode(',', $res['item_id']); // 将包含多个ID的字符串转换成数组
            $result = Db::table('times_yuwen')
                        ->alias('y')
                        ->whereIn('y.id', $item_id)
                        ->field('y.words')  // 选择需要返回的字段
                        ->select();
            $words = '';
            foreach ($result as $key => $value) {
                $words .= $value['words'].'、';
                
            }
            $words = mb_substr($words, 0, -1);
            $res['words'] = $words;
        }
        throw new SuccessException([ 'content' => $res ,'msg' => 'SUCCESS' ]);
    }
}
